package com.flying.server.network;

import com.flying.server.network.msg.ORMsg;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.handler.codec.frame.FrameDecoder;


public class MsgDecoder extends FrameDecoder{
	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {
		System.out.printf("MsgDecoder decode buffer.readableBytes()="+buffer.readableBytes());
		
		//记录当前读取位置
		buffer.markReaderIndex();
		
		if (buffer.readableBytes() < ORMsg.MSG_HEADER_LEN)
		{
			return null;
		}
		
		short msgType = buffer.readShort();
		short msgSeq = buffer.readShort();
		int msglen = buffer.readInt();
		System.out.printf("msgType="+msgType+" seq="+msgSeq+" msglen="+msglen);
		if (buffer.readableBytes() < msglen)
		{
			buffer.resetReaderIndex();
			return null;
		}
		
		ORMsg msg = new ORMsg(msgType,msgSeq,buffer.readBytes(msglen));
		
		return msg;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { 
        e.getCause().printStackTrace();
        
        Channel ch = e.getChannel();
        ch.close();
    }
}
